import { RouteRecordRaw, RouteRecordName } from 'vue-router'
import { asyncRoutes } from '@/router/index'
import settings from '@/config/setting'
import { getUserPromise, getUserMenu } from '@/api/Promise'

export interface routeItem {
  name?: RouteRecordName
  path: string
  hidden?: boolean
  notShowChildren?: boolean
  parent?: routeItem
  children?: routeItem[]
}

export async function resloveMenu(): Promise<routeItem[]> {
  let allRoutes: RouteRecordRaw[]
  if (settings.router && settings.router === 'intelligence') {
    allRoutes = asyncRoutes
  } else {
    const { data } = await getUserMenu()
    allRoutes = data
  }
  let data: any = { menu: null }
  if (!settings.router || settings.router !== 'intelligence') {
    const response = await getUserPromise()
    data = response.data
  }
  const result: routeItem[] = []
  allRoutes.forEach(route => {
    const item = buildItem(data.menu, route)
    if (item) result.push(item)
  })
  return result
}

function buildItem(promise: string[], item: RouteRecordRaw): routeItem | null {
  if (!promise || promise.includes(item.path)) {
    if (item.children && item.children.length > 0) {
      const children: routeItem[] = []
      item.children.forEach((childItem: any) => {
        const ci = buildItem(promise, childItem)
        if (ci) {
          children.push(ci)
        }
      })
      if (children.length === 0) {
        return { name: item.name, path: item.path, notShowChildren: true }
      }
      if (children.length === 1) {
        return children[0]
      }
      return { name: item.name, path: item.path, children }
    } else {
      return { name: item.name, path: item.path, notShowChildren: true }
    }
  } else {
    return null
  }
}

export function isExternal(path: string): boolean {
  return /^(https?:|mailto:|tel:)/.test(path)
}
